#include "..\\include\Lib_Clara.h"
#include "..\\include\Dir.h"
#define fseek lseek

int allocated = 0;
char *tmp;

int fgetc (int file)
{
  char tmp;
  fread(file,&tmp,1);
  return (tmp);
}

char *get_addr (int file)
{
  if (allocated == 0)
  {
    tmp = (char*)malloc(4);
    allocated = 1;
  }
  for (int i = 3 ; i >= 0 ; i--) tmp[i] = fgetc(file);
  return (tmp);
}

int main (void)
{
  int f = _fopen(GetDir(DIR_ELFS_CONFIG | MEM_INTERNAL),L"lib.bin",0x001,0x180,0);
  FSTAT _fst;
  fstat (GetDir(DIR_ELFS_CONFIG | MEM_INTERNAL),L"lib.bin",&_fst);
  int addresses = (_fst.fsize - 8) / 4;
  debug_printf ("\n num: %d \n",addresses);
  char *output = (char*)malloc(40 * addresses + 10);
  memset (output,0,40 * addresses + 10);
  strcat (output,";ElfLibrary converted by bin2lib (mc_kibel)\x0D\x0A");
  strcat (output,"+DEADBEEF ;Fix base address\x0D\x0A");
  fseek (f,8,0);
  int SWI_NUM = 0x112;
  int empty;
  int platform = GetChipID();
  if (platform == 0x8000 || platform == 0x8040) empty = 0xFFFFFFFF;
  else empty = 0;
  for (int i = 1 ; i <= addresses ; i++)
  {
    char *adr = get_addr(f);
    char tmp1[40];
    sprintf (tmp1,"%04X: %08X %02X%02X%02X%02X ; %0X \x0D\x0A", (SWI_NUM - 0x111) * 4 + 0x444, empty, adr[3],adr[2],adr[1],adr[0], SWI_NUM);
    strcat(output,tmp1);
    SWI_NUM++;
  }
  fclose (f);
  int s = _fopen(GetDir(DIR_ELFS_CONFIG | MEM_INTERNAL),L"bin2lib.vkp",WA_Write,0x180,0);
  fwrite( s, output, strlen(output)+1 );
  fclose (s);
  mfree (tmp);
  mfree (output);
  MessageBox(0x6Fffffff,STR("Job finished. Bin2lib.vkp placed in mem_internal | dir_elfs_config"),0,1,0,0);
  return 1;
}

